import type { Claims } from "@/types";
import { storage } from "@/utils";
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";

export interface AuthState {
	claims?: Claims;
	isAuthenticated: boolean;
	login: (claims: Claims) => void;
	logout: () => void;
	isAuthorized: (code: string) => boolean;
}

export const useAuthStore = create<AuthState>()(
	devtools(
		persist(
			(set, get) => ({
				isAuthenticated: false,
				login: (claims: Claims) => {
					set({ claims, isAuthenticated: true });
					storage.setClaims(claims);
				},
				logout: () => {
					set({ claims: undefined, isAuthenticated: false });
					storage.removeClaims();
				},
				isAuthorized: (code: string) => {
					const { isAuthenticated, claims } = get();

					if (!isAuthenticated || !claims) return false;

					if (claims.isSuper) return true;
					if (!claims.features) return false;

					return claims.features.includes(code);
				},
			}),
			{
				name: "auth",
			},
		),
	),
);
